﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Json;

namespace BingApp
{
    public partial class Results : Page
    {
        public List<BingWebResult> webProperty { get; set; }
        public List<BingImageResult> imageProperty { get; set; }
        
        public String searchQuery { get; set; }
      

        public Results()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Results_Loaded);
        }

        void Results_Loaded(object sender, RoutedEventArgs e)
        {
            SearchQueryText.Text = "Bing Results for: " + searchQuery + " first 50 Results";
            populateResultsContent();
        }

        private void populateResultsContent()
        {
            foreach (BingImageResult bing_image in imageProperty)
            {
                Image image = new Image();
                image.Tag = bing_image;
                image.MouseLeftButtonDown += new MouseButtonEventHandler(image_MouseLeftButtonDown);
                ImageSource imagesource = new System.Windows.Media.Imaging.BitmapImage(new Uri(bing_image.ToString()));
                Rectangle rectangle_spacer = new Rectangle();
                rectangle_spacer.Height = 30;
                image.Stretch = Stretch.None;
                image.HorizontalAlignment = HorizontalAlignment.Left;
                image.Source = imagesource;

                stackImages.Children.Add(image);
                stackImages.Children.Add(rectangle_spacer);
            }
            foreach (BingWebResult bing_web in webProperty)
            {
                Rectangle rectangle_spacer = new Rectangle();
                rectangle_spacer.Height = 10;

                HyperlinkButton web_title = new HyperlinkButton();
                web_title.FontSize = 14;
                web_title.FontFamily = new FontFamily("Arial");
                web_title.Foreground = new SolidColorBrush(Colors.Blue);
                web_title.Content = bing_web.BingResultTitle;
                web_title.Tag = bing_web;
                web_title.Click += new RoutedEventHandler(web_title_Click);
               
                TextBlock web_description = new TextBlock();
                web_description.Text = bing_web.BingResultDescription;

                webStack.Children.Add(web_title);
                webStack.Children.Add(web_description);
                webStack.Children.Add(rectangle_spacer);
            }
        }

        void web_title_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton link_button = (HyperlinkButton)e.OriginalSource;
            BingWebResult cached_web = link_button.Tag as BingWebResult;
            HtmlPage.Window.Navigate(new Uri(cached_web.BingResultUrl), "_blank");

            //connectPipe(cached_web.BingResultUrl);
        }

        void connectPipe(string source)
        {
            string pipe = "http://pipes.yahooapis.com/pipes/pipe.run?_id=60956586e21e535cb2ac841cafde4e5b&_render=json&SiteFeed=";
            source = "digg.com";
            string url = string.Concat(pipe, HttpUtility.UrlEncode(source));

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
            request.BeginGetResponse(new AsyncCallback(ResponseHandler), request);
        }

        private void ResponseHandler(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
                StreamReader stream_reader = null;
                StringBuilder data = new StringBuilder();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    stream_reader = new StreamReader(response.GetResponseStream());
                    string json = "";

                    while ((json = stream_reader.ReadLine()) != null)
                    {
                        data.Append(json);
                    }
                }
                
                stream_reader.Dispose();
                response.GetResponseStream().Close();
                response.Close();

                if(data.Length > 1)
                {
                    processHtmlJson(data.ToString());
                }
            }
            catch (Exception err)
            {
            }

        }

        private void processHtmlJson(string json_data)
        {
            JsonValue json = JsonValue.Parse(json_data);
           
            if(json.ContainsKey("count"))
            {
                int count = (int)json["count"];
                if (count > 0)
                {
                    if (json.ContainsKey("value"))
                    {
                        json = json["value"];

                        if (json.ContainsKey("items"))
                        {
                            JsonArray html_content_array = (JsonArray)json["items"];
                            if (html_content_array.Count > 0)
                            {
                                string html = "";

                                for (int i = 0; i < html_content_array.Count; i++)
                                {
                                    JsonValue htmlBlock = html_content_array[i];

                                    if(htmlBlock.ContainsKey("content"))
                                    {
                                        html += htmlBlock["content"].ToString().Trim();
                                    }
                                }
                                //showWebWindow show_web = new showWebWindow(showChildWindow);
                                //this.Dispatcher.BeginInvoke(show_web, new object[]
                                //{
                                //    html
                                //});
                            }
                            
                        }
                    }
                }
            }
        }
        //delegate void showWebWindow(string html);
        //void showChildWindow(string html)
        //{
        //    ChildWindow child_window = new ChildWindow();
        //    child_window.Content = place_holder;
        //    child_window.Show();
        //}

        void image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Image castImage = e.OriginalSource as Image;

            BingImageResult cached_image = castImage.Tag as BingImageResult;

            Image childWindow_bing_image = new Image();
            ImageSource imagesource = new System.Windows.Media.Imaging.BitmapImage(new Uri(cached_image.BingResultImageMedia));
            childWindow_bing_image.Source = imagesource;

            ChildWindow child_window = new ChildWindow();
            child_window.LostFocus += new RoutedEventHandler(child_window_LostFocus);
            child_window.VerticalAlignment = VerticalAlignment.Center;
            child_window.HorizontalAlignment = HorizontalAlignment.Center;
            child_window.Content = childWindow_bing_image;
            child_window.Width = childWindow_bing_image.Width - 10;
            child_window.Height = childWindow_bing_image.Height - 10;
            child_window.Title = cached_image.BingResultImageTitle;
            child_window.Show();
        }

        void child_window_LostFocus(object sender, RoutedEventArgs e)
        {
            ChildWindow window = (ChildWindow)e.OriginalSource;
            window.Close();
        }
    }
}
